package ctu.edu.vn.musicmanager.accessdata;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import ctu.edu.vn.musicmanager.object.Music;


public class MusicORM {
	
	 private HibernateTemplate hibernateTemplate;

	    public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
	        this.hibernateTemplate = hibernateTemplate;
	    }

	    public HibernateTemplate getHibernateTemplate(){
	        return hibernateTemplate;
	    }
	    public Music getMusic(final Serializable id){        
	        HibernateCallback callback = new HibernateCallback() {
	            public Object doInHibernate(Session session) 
	                throws HibernateException,SQLException {
	                return session.load(Music.class, id);
	            }
	        };        
	        return (Music)hibernateTemplate.execute(callback);
	    }
	    
	    public List<Music> fetchAllMusic() {
	        return hibernateTemplate.loadAll(Music.class);
	    }
	    
	    public void deleteMusic(final Serializable id) {
	    	Object record = hibernateTemplate.load(Music.class, id);
	    	hibernateTemplate.delete(record);
	    }

	    public void save(final Music music) {
	        HibernateCallback callback = new HibernateCallback() {
	            public Object doInHibernate(Session session) 
	                throws HibernateException,SQLException {
	                session.save(music);
	                return null;
	            }
	        };          
	        hibernateTemplate.execute(callback);
	    }
	    
	    public void update(final Music music) {
	             hibernateTemplate.update(music);
	    }
	    public void delete(final Music music) {
	    		hibernateTemplate.delete(music);    
	    }
	    public int getLastID() {
	    	int id = 0;
	    	//List<Music> ds1 = hibernateTemplate.find("SELECT MAX(ID) FROM MUSIC");
	    	List<Music> ds = hibernateTemplate.loadAll(Music.class);
	    	for(Music ms : ds)
	    		id = ms.getID();
	    	return id;
	    }
	   
}
